package com.easypan.controller;

import com.easypan.Service.FileInfoService;
import com.easypan.entity.configA.cofig;
import com.easypan.entity.constants.Constants;
import com.easypan.entity.dto.DownloadFileDto;
import com.easypan.entity.dto.SessionwebUserDto;
import com.easypan.entity.po.FileInfo;
import com.easypan.entity.query.FileInfoQuery;
import com.easypan.entity.vo.R;
import com.easypan.enums.FileCategoryEnums;
import com.easypan.enums.FileFolderTypeEnums;
import com.easypan.enums.ResponseCodeEnum;
import com.easypan.exception.BusinessException;
import com.easypan.util.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

public class CommonFileController {
    @Resource
    private cofig cofig;
    @Autowired
    FileInfoService fileInfoService;
    protected R getImage(HttpServletResponse httpServletResponse, HttpSession session, String imageFolder, String imageName) throws IOException {
   //显示文件 拼凑文件真实地址把 -too 文件userid太简单 后续敏感接口的判断一下
        //先判断一下
        if(StringUtils.isEmpty(imageFolder) || StringUtils.isEmpty(imageName))
        {
            return R.error("文件参数错误");
        }
        //文件本地目录拼凑
        String projectFolder = cofig.getProjectFolder()+ Constants.FILE_FOLDER_FILE+imageFolder+ "/"+imageName;

        //拿出后缀写进响应体
        String fileSuffix = StringTools.getFileSuffix(imageName);
        fileSuffix = fileSuffix.replace(".", "");//取出点
        String contentType = "image/" + fileSuffix;
        httpServletResponse.setContentType(contentType);
        httpServletResponse.setHeader("Cache-Control", "max-age=2592000");
        //开始读 ->往对方的读缓冲区给值
        readFile(projectFolder,httpServletResponse);
        return R.success("test");
    }

    public void readFile(String projectFolder, HttpServletResponse httpServletResponse) throws IOException {
        FileInputStream fileInputStream= null;
        try {
            fileInputStream = new FileInputStream(new File(projectFolder));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        ServletOutputStream outputStream=httpServletResponse.getOutputStream();

        int len=0;

        byte[] bytes=new byte[1024];

        //读取文件内容拼凑发送
        //读内容到缓冲器 另利用输入流进行发送
        while ( (len=fileInputStream.read(bytes) ) != -1     )
        {
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        //关闭资源
        outputStream.close();
        fileInputStream.close();

    }

    protected R getFile(HttpServletResponse httpServletResponse, String mp4Info, HttpSession session) {
        SessionwebUserDto webUserDto = (SessionwebUserDto) session.getAttribute("session_key");
        if (webUserDto == null) {
            return R.error("用户数据错误");
        }
        String path = null;
        if (mp4Info.endsWith(".ts")) {
        //http://easypan.wuhancoder.com/api/file/ts/getVideoInfo/1194663411_0000.ts
         //拿出ts
            //too 秒传导致的视频秒播放问题
            String[] tsArray = mp4Info.split("_");
            String realFile = tsArray[0];//拿到真实我文件ID
            FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(realFile, String.valueOf(webUserDto.getUserId()));
            if(fileInfo==null)
            {
                R.error("用户不匹配");
            }
            ///202312/11194663411.mp4
            String fileName = fileInfo.getFilePath(); //拿出路径
            //拼凑文件夹
         fileName=StringTools.getFileNameNoSuffix(fileName)+"/"+mp4Info; ///202312/11194663411+/+1194663411_0000.ts
            path = cofig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileName;
            ///H:\myworkspace-java\tempFolderName\file\ ///202312/11194663411+/+1194663411_0000.ts

        } else//读mu38
        {
            //防止其他人通过遍历方法拿取到它人的文件
            FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(mp4Info, String.valueOf(webUserDto.getUserId()));

            if (fileInfo == null) {
                return R.error("当前用户没有该文件");
            }
            //判断文件类型 --这里是一个通用接口
            if (FileCategoryEnums.VIDEO.getCategory().equals(fileInfo.getFileCategory())) {
                //视频文件
                //去掉文件后缀
                String fileNameNoSuffix = StringTools.getFileNameNoSuffix(fileInfo.getFilePath());
                //拼凑真的文件目录 前置 +file+
                path = cofig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileNameNoSuffix + "/" + Constants.M3U8_NAME;
            } else {
                //统一规范为其他文件

                path = cofig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileInfo.getFilePath();
            }


        }
        readFile(httpServletResponse, path);
        return R.success("成功");
    }
    protected R getFile(HttpServletResponse httpServletResponse, String mp4Info, String userid) {


        String path = null;
        if (mp4Info.endsWith(".ts")) {
            //http://easypan.wuhancoder.com/api/file/ts/getVideoInfo/1194663411_0000.ts
            //拿出ts
            //too 秒传导致的视频秒播放问题
            String[] tsArray = mp4Info.split("_");
            String realFile = tsArray[0];//拿到真实我文件ID
            FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(realFile, String.valueOf(userid));
            if(fileInfo==null)
            {
                R.error("用户不匹配");
            }
            ///202312/11194663411.mp4
            String fileName = fileInfo.getFilePath(); //拿出路径
            //拼凑文件夹
            fileName=StringTools.getFileNameNoSuffix(fileName)+"/"+mp4Info; ///202312/11194663411+/+1194663411_0000.ts
            path = cofig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileName;
            ///H:\myworkspace-java\tempFolderName\file\ ///202312/11194663411+/+1194663411_0000.ts

        } else//读mu38
        {
            //防止其他人通过遍历方法拿取到它人的文件
            FileInfo fileInfo = fileInfoService.getFileInfoByFileIdAndUserId(mp4Info, String.valueOf(userid));

            if (fileInfo == null) {
                return R.error("当前用户没有该文件");
            }
            //判断文件类型 --这里是一个通用接口
            if (FileCategoryEnums.VIDEO.getCategory().equals(fileInfo.getFileCategory())) {
                //视频文件
                //去掉文件后缀
                String fileNameNoSuffix = StringTools.getFileNameNoSuffix(fileInfo.getFilePath());
                //拼凑真的文件目录 前置 +file+
                path = cofig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileNameNoSuffix + "/" + Constants.M3U8_NAME;
            } else {
                //统一规范为其他文件

                path = cofig.getProjectFolder() + Constants.FILE_FOLDER_FILE + fileInfo.getFilePath();
            }


        }
        readFile(httpServletResponse, path);
        return R.success("成功");
    }
    protected void readFile(HttpServletResponse response, String filePath) {
        if (!StringTools.pathIsOk(filePath)) {
            return;
        }
        OutputStream out = null;
        FileInputStream in = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            in = new FileInputStream(file);
            byte[] byteData = new byte[1024];
            out = response.getOutputStream();
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len);
            }
            out.flush();
        } catch (Exception e) {

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {

                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {

                }
            }
        }
    }

    protected R getFolderInfo(String path, Integer userId) {
//返回层级目录
        String[] pathArray = path.split("/");//拿取每一个层级目录
        FileInfoQuery infoQuery = new FileInfoQuery();
        infoQuery.setUserId(userId);
        infoQuery.setFileIdArray(pathArray);

        infoQuery.setFolderType(FileFolderTypeEnums.FOLDER.getType());

        String orderBy = "field(file_id,\"" + org.apache.commons.lang3.StringUtils.join(pathArray, "\",\"") + "\")";//拼凑根据目录id的顺序返回
        //+转义字符
        infoQuery.setOrderBy(orderBy);
        //查询出来的是一个集合类型
        List<FileInfo> fileInfoList = fileInfoService.findListByParam(infoQuery);

        return R.success(fileInfoList);
    }


}
